package com.deng.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deng.common.lang.Result;
import com.deng.entity.Post;
import com.deng.vo.PostVo;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/admin")
//admin用户的操作
public class AdminController extends BaseController{
    @ResponseBody
    @RequestMapping("/jie-set")
    //根据field来判断是1置顶，加精还是删除操作,rank取0，1,表示是否置顶
    public Result jetSet(Long id,Integer rank,String field){
        Post post=postService.getById(id);
        Assert.notNull(post,"这篇文章已被删除");
        if("delete".equals(field)){
            postService.removeById(id);
        }else if("status".equals(field)){
            post.setRecommend(rank==1);
        }else if("stick".equals(field)){
            post.setLevel(rank);
        }
        postService.updateById(post);
        return Result.success();
    }
    //管理员同步数据库与Es
    @ResponseBody
    @PostMapping("/initEsData")
    public Result initEsData(){
        //分批同步,先从数据库中取数据
        int size=10000;
        long total=0;
        Page page=new Page();
        for(int i=1;i<1000;i++){
            page.setCurrent(i);
            //从数据库取数据
            IPage<PostVo> paging= postService.paging(page,null,null,null,null,null);
            //将数据同步到ES
           int num= searchService.initEsData(paging.getRecords());
           total+=num;
           //查询完成
            if(paging.getRecords().size()<size){
                break;
            }
        }
        return Result.success("Es索引初始化成功，共"+total+"条记录",null);
    }
}
